<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'
import { ElMessage } from 'element-plus'
import {
  Lock,
  User,
  Message,
  Avatar,
  View,
  Hide,
} from '@element-plus/icons-vue'

// 类型定义
interface LoginForm {
  username: string
  password: string
}

interface RegisterForm {
  username: string
  nickname: string
  email: string
  password: string
  confirmPassword: string
}

// 响应式状态
const activeTab = ref(1)
const loading = ref(false)
const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const loginFormRef = ref<any>(null)
const registerFormRef = ref<any>(null)

const loginForm = ref<LoginForm>({
  username: '',
  password: '',
})

const registerForm = ref<RegisterForm>({
  username: '',
  nickname: '',
  email: '',
  password: '',
  confirmPassword: '',
})

// 添加密码可见性控制
const passwordVisible = ref(false)

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}

// 登录处理
const handleLogin = async (formEl: any) => {
  if (!formEl) return

  await formEl.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        await authStore.login({
          username: loginForm.value.username,
          password: loginForm.value.password,
        })
        const redirectUrl = (route.query.redirect as string) || '/'
        router.push(redirectUrl)
        ElMessage.success('登录成功')
      } catch (error: any) {
        ElMessage.error(error.message || '登录失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 注册处理
const handleRegister = async (formEl: any) => {
  if (!formEl) return

  await formEl.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        await authStore.register({
          username: registerForm.value.username,
          nickname: registerForm.value.nickname,
          email: registerForm.value.email,
          password: registerForm.value.password,
        })
        ElMessage.success('注册成功')
        activeTab.value = 1 // 切换到登录页
      } catch (error: any) {
        ElMessage.error(error.message || '注册失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 切换登录/注册
const switchTab = (tab: number) => {
  activeTab.value = tab
}

onMounted(() => {
  activeTab.value = Number(route.query.login) || 1
})
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>{{ activeTab === 1 ? '欢迎回来' : '创建账号' }}</h2>
        <p>
          {{
            activeTab === 1
              ? '使用您的账号登录系统'
              : '填写以下信息创建您的账号'
          }}
        </p>
      </div>

      <!-- 登录表单 -->
      <el-form
        v-if="activeTab === 1"
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            :prefix-icon="User"
            placeholder="用户名" />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            :prefix-icon="Lock"
            :type="passwordVisible ? 'text' : 'password'"
            placeholder="请输入密码"
            :show-password="false"
            @keyup.enter="handleLogin(loginFormRef)">
            <template #suffix>
              <el-icon
                class="password-eye"
                @click="passwordVisible = !passwordVisible">
                <View v-if="passwordVisible" />
                <Hide v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <div class="form-footer">
          <el-checkbox>记住我</el-checkbox>
          <el-link type="primary">忘记密码？</el-link>
        </div>

        <el-button
          type="primary"
          :loading="loading"
          class="submit-btn"
          @click="handleLogin(loginFormRef)">
          登录
        </el-button>

        <div class="switch-tab">
          还没有账号？
          <el-link type="primary" @click="switchTab(2)">立即注册</el-link>
        </div>
      </el-form>

      <!-- 注册表单 -->
      <el-form
        v-else
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form">
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            :prefix-icon="User"
            placeholder="用户名" />
        </el-form-item>

        <el-form-item prop="nickname">
          <el-input
            v-model="registerForm.nickname"
            :prefix-icon="Avatar"
            placeholder="昵称" />
        </el-form-item>

        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            :prefix-icon="Message"
            placeholder="邮箱" />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            :prefix-icon="Lock"
            :type="passwordVisible ? 'text' : 'password'"
            placeholder="请输入密码">
            <template #suffix>
              <el-icon
                class="password-eye"
                @click="passwordVisible = !passwordVisible">
                <View v-if="passwordVisible" />
                <Hide v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            :prefix-icon="Lock"
            :type="passwordVisible ? 'text' : 'password'"
            placeholder="请确认密码">
            <template #suffix>
              <el-icon
                class="password-eye"
                @click="passwordVisible = !passwordVisible">
                <View v-if="passwordVisible" />
                <Hide v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-button
          type="primary"
          :loading="loading"
          class="submit-btn"
          @click="handleRegister(registerFormRef)">
          注册
        </el-button>

        <div class="switch-tab">
          已有账号？
          <el-link type="primary" @click="switchTab(1)">立即登录</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  position: relative;
  overflow: hidden;

  // 背景图设置
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    // 使用高质量在线背景图
    background-image: url('https://images.pexels.com/photos/1181671/pexels-photo-1181671.jpeg');
    /* 备选背景图：
    1. https://images.pexels.com/photos/1714208/pexels-photo-1714208.jpeg (深色科技风)
    2. https://images.pexels.com/photos/325185/pexels-photo-325185.jpeg (现代简约)
    3. https://images.pexels.com/photos/2387793/pexels-photo-2387793.jpeg (抽象几何)
    4. https://images.pexels.com/photos/1181406/pexels-photo-1181406.jpeg (商务办公)
    5. https://images.pexels.com/photos/1181671/pexels-photo-1181671.jpeg (科技感强)
    */
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    filter: blur(2px);
    transform: scale(1.1);
  }

  // 暗色叠加层 - 调整为更适合当前背景的渐变
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      135deg,
      rgba(18, 18, 18, 0.7) 0%,
      rgba(18, 18, 18, 0.5) 100%
    );
    backdrop-filter: blur(5px);
  }

  .login-box {
    position: relative;
    width: 420px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(8px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    z-index: 1;
    animation: fadeIn 0.5s ease;

    .login-header {
      text-align: center;
      margin-bottom: 40px;

      h2 {
        font-size: 28px;
        background: linear-gradient(45deg, #2196f3, #1565c0);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: 8px;
      }

      p {
        color: #666;
        font-size: 14px;
      }
    }

    .login-form,
    .register-form {
      .el-input {
        --el-input-height: 44px;
        margin-bottom: 5px;

        :deep(.el-input__wrapper) {
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
          transition: all 0.3s ease;

          &:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
          }

          &.is-focus {
            box-shadow: 0 4px 12px rgba(33, 150, 243, 0.1);
          }
        }
      }

      .form-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 20px 0;
      }

      .submit-btn {
        width: 100%;
        height: 44px;
        font-size: 16px;
        margin-top: 20px;
        background: linear-gradient(45deg, #2196f3, #1565c0);
        border: none;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);
        }
      }

      .switch-tab {
        text-align: center;
        margin-top: 20px;
        color: #666;
      }
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式设计
@media screen and (max-width: 576px) {
  .login-box {
    width: 90% !important;
    padding: 20px !important;
    margin: 20px;
  }
}

.password-eye {
  cursor: pointer;
  color: var(--el-text-color-secondary);
  transition: color 0.3s;

  &:hover {
    color: var(--el-text-color-primary);
  }
}

:deep(.el-input__suffix) {
  cursor: pointer;
  padding: 0 8px;
}
</style>
